from flask import Flask, request, jsonify
import pymysql

app = Flask(__name__, static_folder='')

# 数据库连接配置
db_config = {
    'host': 'localhost',
    'user': 'root',  # 替换为您的MySQL用户名
    'password': 'ww5382672',  # 替换为您的MySQL密码
    'database': 'liuyuxin',  # 替换为您的数据库名
    'charset': 'utf8mb4',
    'cursorclass': pymysql.cursors.DictCursor
}


@app.route('/submit_diary', methods=['POST'])
def submit_diary():
    try:
        # 获取表单数据
        date = request.form['date']
        mood = request.form['mood']
        weather = request.form['weather']
        event = request.form['event']

        # 连接到数据库
        connection = pymysql.connect(**db_config)

        try:
            with connection.cursor() as cursor:
                # 插入数据
                sql = "INSERT INTO diary_entries (date, mood, weather, event) VALUES (%s, %s, %s, %s)"
                cursor.execute(sql, (date, mood, weather, event))
            # 提交事务
            connection.commit()
            return jsonify({'status': 'success', 'message': '日记提交成功！'}), 200
        finally:
            connection.close()
    except Exception as e:
        return jsonify({'status': 'error', 'message': str(e)}), 500
@app.route('/',methods=['GET','POST'])
def index():
    return app.send_static_file('index.html')  # 假设HTML文件名为index.html

if __name__ == '__main__':
    app.run(host='0.0.0.0', debug=True)
